package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.common.util.LoginUserInfo;
import com.heima.common.util.UserInfoThreadLocal;
import com.heima.model.behavior.dto.ArticleBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.BehaviorRedisKeyEnum;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServcieImpl implements ApBehaviorServcie {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询用户文章行为
     * 收藏、点赞、关注、不喜欢等行为
     * @param dto 文章行为参数
     * @return ResponseResult
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        // 1.检查参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.error(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2.获取用户信息
        LoginUserInfo user = UserInfoThreadLocal.get();
        if (user == null) {
            return ResponseResult.success(new HashMap<>());
        }

        // 3.定义初始值
        boolean isUnlike = false;
        boolean isLike = false;
        boolean isCollection = false;
        boolean isFollow = false;

        // 4.查询收藏行为
        String collectionKey = BehaviorRedisKeyEnum.COLLECTION_BEHAVIOR_PREFIX.buildKey(dto.getArticleId());
        isCollection = Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(collectionKey, String.valueOf(user.getId())));

        // 5.查询点赞行为
        String likeKey = BehaviorRedisKeyEnum.LIKES_BEHAVIOR_PREFIX.buildKey(dto.getArticleId());
        isLike = Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(likeKey, String.valueOf(user.getId())));

        // 6.查询关注行为
        String followKey = BehaviorRedisKeyEnum.FOLLOW_BEHAVIOR_PREFIX.buildKey(user.getId());
        isFollow = Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(followKey, String.valueOf(dto.getAuthorId())));

        // 7.查询不喜欢行为
        String unLikeKey = BehaviorRedisKeyEnum.UNLIKES_BEHAVIOR_PREFIX.buildKey(dto.getArticleId());
        isUnlike = Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(unLikeKey, String.valueOf(user.getId())));

        // 8.封装结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isFollow);
        resultMap.put("islike", isLike);
        resultMap.put("isunlike", isUnlike);
        resultMap.put("iscollection", isCollection);
        return ResponseResult.success(resultMap);
    }
}
